package cn.dw.utils;

import java.util.List;

import cn.dw.domain.SNSUserInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class AdvancedUtil {
	public static String getOauth2AccessToken(String appId, String appSecret, String code) {
		String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

		requestUrl = requestUrl.replace("APPID", appId);
		requestUrl = requestUrl.replace("SECRET", appSecret);
		requestUrl = requestUrl.replace("CODE", code);

		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);

		String openid = null;
		if (jsonObject != null) {
			try {
				openid = jsonObject.getString("openid");
			} catch (Exception e) {
				System.err.println("获取网页授权凭证失败 errcode:,errMsg:");
			}
		}
		return openid;
	}

	@SuppressWarnings({ "deprecation", "unchecked" })
	public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
		SNSUserInfo snsUserInfo = null;

		String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);

		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
		if (jsonObject != null) {
			try {
				snsUserInfo = new SNSUserInfo();

				snsUserInfo.setOpenId(jsonObject.getString("openid"));

				snsUserInfo.setNickname(jsonObject.getString("nickname"));

				snsUserInfo.setSex(jsonObject.getInt("sex"));

				snsUserInfo.setCountry(jsonObject.getString("country"));

				snsUserInfo.setProvince(jsonObject.getString("province"));

				snsUserInfo.setCity(jsonObject.getString("city"));

				snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));

				snsUserInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
			} catch (Exception e) {
				snsUserInfo = null;
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");

				System.err.println("获取用户信息失败 errcode:" + errorCode + ",errMsg:" + errorMsg);
			}
		}
		return snsUserInfo;
	}
}
